#include "HovercraftRadio.h"
#include "../arduinomega/HardwareSerial.h"
/*
 * RadioReceiver.cpp
 *
 *  Created on: Feb 4, 2010
 *      Author: fmason
 */
/*
* Radio		Seeeduino
*  Vcc				48
*   CE				49
*  CSN				47
*  SCK				52
* MOSI				51
* MISO				50
*  IRQ				2
*  GND				GND
*/
const int MESSAGE_SIZE = 20;

static int message_id;
static int serviceable;

uint8_t rx_addr[] = { 0x05, 0x04, 0x03, 0x02, 0x01 };//hovercraft address
uint8_t tx_addr[] = { 0x01, 0x02, 0x03, 0x04, 0x05 };//remote joystick address

radiopacket_t packet;

void setupRadioReceiver()
{
	Serial.println( "" );
	Serial.println( "HovercraftRadio.cpp:" );
	Serial.println( "" );
	Serial.println( "Cycling Radio Power..." );

	//Reset the radio with a power cycle
	pinMode( 48, OUTPUT );
	Serial.println( "set pin mode to output" );
	digitalWrite( 48, LOW );
	Serial.println( "turned power off" );
	delay( 1000 );
	Serial.println( "waited for one second" );
	digitalWrite( 48, HIGH );
	Serial.println( "turned power on" );
	delay( 11 );

	Serial.println( "Radio Power Cycled" );

	//initialize and configure the radio
	Serial.println( "Initializing Radio..." );
	Radio_Init();
	Serial.println( "Radio Initialized" );

	Serial.println( "Configuring Radio..." );
	Radio_Configure_Rx(RADIO_PIPE_0, rx_addr, ENABLE);
	Radio_Configure(RADIO_2MBPS, RADIO_HIGHEST_POWER);
	Serial.println( "Radio Configured" );

}

int is_serviceable()
{
	return serviceable;
}

void clear_serviceable()
{
	serviceable = false;
}

int get_message_id()
{
	return message_id;
}

//handles incoming radio requests
void radio_rxhandler(uint8_t pipe_number)
{
	Serial.begin( BAUD_RATE );
	// Receive the message
	Radio_Receive( &packet );

	if( packet.type == MESSAGE )
	{
		serviceable = true;
		message_id = packet.payload.message.messageid;
	}
	else
	{
		Serial.print( "Received non-MESSAGE packet type" );
	}
}

void sendSonarOutput( int value )
{
	packet.payload.reading.messageid = SONAR_READING;
	packet.payload.reading.value = value;
	Radio_Transmit(&packet, RADIO_WAIT_FOR_TX);
	delay( 20 );
}
